<template>
  <div class="project-setting-view">
    <p class="project-setting-title">
      回收设置
      <span class="small-font-size ml20 text-secondary-color">
        自定义问卷收集收集时间，次数，以及限制填写环境等
      </span>
    </p>
    <el-divider />
    <el-form
      ref="writeSettingForm"
      :model="writeSettingForm"
      :rules="settingRules"
      label-position="left"
    >
      <div class="setting-item">
        <p class="label">
          填试卷时自动暂存数据
          <el-tooltip
            class="item"
            content="开启后将会保存未提交的数据，再次进入问卷页会提示是否继续使用上次未提交的数据"
            effect="dark"
            placement="top-start"
          >
            <i class="el-icon-warning" />
          </el-tooltip>
        </p>
        <el-switch v-model="writeSettingForm.saveNotSubmitStatus" />
      </div>
      <div class="setting-item">
        <p class="label">
          填充上次填写数据
          <el-tooltip
            class="item"
            content="开启后将会在浏览器本地保存提交的数据，再次进入问卷页会提示是否继续使用上次提交的数据"
            effect="dark"
            placement="top-start"
          >
            <i class="el-icon-warning" />
          </el-tooltip>
        </p>
        <el-switch v-model="writeSettingForm.saveSubmitStatus" />
      </div>
      <div class="setting-item">
        <p class="label">
          密码填写
          <el-tooltip
            class="item"
            content="开启后需要输入密码才能进入填写页面"
            effect="dark"
            placement="top-start"
          >
            <i class="el-icon-warning" />
          </el-tooltip>
        </p>
        <el-switch v-model="writeSettingForm.passwordWriteStatus" />
      </div>
      <div v-if="writeSettingForm.passwordWriteStatus">
        <el-form-item
          :rules="[
            { required: true, message: '请输入填写密码', trigger: 'blur' }
          ]"
          prop="writePassword"
        >
          <el-input
            v-model="writeSettingForm.writePassword"
            placeholder="请输入填写密码"
          />
        </el-form-item>
      </div>
      <div class="setting-item">
        <p class="label">
          每个微信答题次数限制
        </p>
        <el-switch
          v-model="writeSettingForm.wxWriteCountLimitStatus"
          @change="
            () => {
              writeSettingForm.recordWxUser = true
              writeSettingForm.onlyWxWrite = true
            }
          "
        />
      </div>
      <div v-if="writeSettingForm.wxWriteCountLimitStatus">
        <el-row>
          <el-col :span="8">
            <el-select v-model="writeSettingForm.wxWriteCountLimitDateType">
              <el-option v-for="d in dateRangeList"
                         :key="d.value"
                         :label="d.label"
                         :value="d.value"
              >
                {{ d.label }}
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            答题
            <el-input-number v-model="writeSettingForm.wxWriteCountLimit" :min="1" />
            次
          </el-col>
        </el-row>
        <el-input v-model="writeSettingForm.wxWriteCountLimitText" class="mt10"
                  placeholder="该微信已经提交过数据，不可重复提交，有问题请与问卷发布者联系"
        />
      </div>
      <div class="setting-item">
        <p class="label">
          每个IP答题次数限制
          <el-tooltip placement="top-start" content=" 此属性用于指定每一个IP地址只能提交一次问卷，可以防止用户在同一台计算机上进行多次提交。">
            <i class="el-icon-warning" />
          </el-tooltip>
        </p>
        <el-switch v-model="writeSettingForm.ipWriteCountLimitStatus" />
      </div>
      <div v-if="writeSettingForm.ipWriteCountLimitStatus">
        <el-row>
          <el-col :span="8">
            <el-select v-model="writeSettingForm.ipWriteCountLimitDateType">
              <el-option v-for="d in dateRangeList"
                         :key="d.value"
                         :label="d.label"
                         :value="d.value"
              >
                {{ d.label }}
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            答题
            <el-input-number v-model="writeSettingForm.ipWriteCountLimit" :min="1" />
            次
          </el-col>
        </el-row>
        <el-input v-model="writeSettingForm.ipWriteCountLimitText" class="mt10"
                  placeholder="该IP已经提交过数据，不可重复提交，有问题请与问卷发布者联系"
        />
      </div>
      <div class="setting-item">
        <p class="label">
          设定答题次数上限
          <el-tooltip placement="top-start" content="当答题次数达到上限后，问卷将无法提交数据，进入将显示提示文案">
            <i class="el-icon-warning" />
          </el-tooltip>
        </p>
        <el-switch v-model="writeSettingForm.totalWriteCountLimitStatus" />
      </div>
      <div v-if="writeSettingForm.totalWriteCountLimitStatus">
        <el-row>
          <el-col :span="8">
            <el-select v-model="writeSettingForm.totalWriteCountLimitDateType">
              <el-option v-for="d in dateRangeList"
                         :key="d.value"
                         :label="d.label"
                         :value="d.value"
              >
                {{ d.label }}
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            答题
            <el-input-number v-model="writeSettingForm.totalWriteCountLimit" :min="1" />
            次
          </el-col>
        </el-row>
        <el-input v-model="writeSettingForm.totalWriteCountLimitText" class="mt10"
                  placeholder="该问卷收集数据已经达到上限，有问题请与问卷发布者联系"
        />
      </div>
      <div class="setting-item">
        <p class="label">
          允许填写时间
          <el-tooltip placement="top-start" content="当进入设置的时间范围内，用户能访问问卷并提交数据，否则将会显示对应文案">
            <i class="el-icon-warning" />
          </el-tooltip>
        </p>
        <el-switch v-model="writeSettingForm.writeInterviewTimeStatus" />
      </div>
      <div v-if="writeSettingForm.writeInterviewTimeStatus">
        <el-row>
          <el-col :span="5">
            <el-checkbox v-model="writeSettingForm.writeInterviewDayTimeStatus">
              限制每天访问的时间范围
            </el-checkbox>
          </el-col>
        </el-row>
        <div v-if="writeSettingForm.writeInterviewDayTimeStatus">
          <el-row class="mt10">
            <el-col :span="13">
              <el-date-picker
                v-model="writeSettingForm.writeInterviewDateRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-col>
          </el-row>
          <el-row class="mt10">
            <el-col :span="13">
              <el-time-picker
                v-model="writeSettingForm.writeInterviewTimeRange"
                is-range
                range-separator="-"
                value-format="HH:mm:ss"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
              />
            </el-col>
          </el-row>
        </div>

        <el-row v-else class="mt10">
          <el-col :span="12">
            <el-date-picker
              v-model="writeSettingForm.writeInterviewDateTimeRange"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-col>
        </el-row>
        <div class="checkbox-group mt10">
          <el-checkbox-group v-model="writeSettingForm.writeInterviewTimeWhichDays">
            <el-checkbox label="2">
              周一
            </el-checkbox>
            <el-checkbox label="3">
              周二
            </el-checkbox>
            <el-checkbox label="4">
              周三
            </el-checkbox>
            <el-checkbox label="5">
              周四
            </el-checkbox>
            <el-checkbox label="6">
              周五
            </el-checkbox>
            <el-checkbox label="7">
              周六
            </el-checkbox>
            <el-checkbox label="1">
              周日
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <el-input v-model="writeSettingForm.writeInterviewTimeText" class="mt10"
                  placeholder="此问卷设置了访问时间，当前时间无法访问，有问题请与问卷发布者联系"
        />
      </div>
      <div class="setting-item">
        <p class="label">
          只能在微信中填写
        </p>
        <el-switch
          v-model="writeSettingForm.onlyWxWrite"
          @change=" val => {
            if (!writeSettingForm.onlyWxWrite && !val) {
              writeSettingForm.recordWxUser = false
            }
          }"
        />
      </div>
      <div class="setting-item">
        <p class="label">
          记录微信用户个人信息
        </p>
        <el-switch
          v-model="writeSettingForm.recordWxUser"
          @change="val => {
            if (!writeSettingForm.onlyWxWrite && val) {
              writeSettingForm.onlyWxWrite = true
            }
          }
          "
        />
      </div>
      <div class="setting-item">
        <p class="label">
          开启短信验证码
        </p>
        <el-switch
          v-model="writeSettingForm.openVerificationCodeLogin"
        />
      </div>
      
      <div class="setting-item">
        <p class="label">
          开启答题样本库
        </p>
        <el-switch
          v-model="writeSettingForm.openSample"
          @change="getTypeTree"
        />
      </div>
      <div v-if="writeSettingForm.openSample" class="sampleList">
        <p class="label" style="color: #1890ff !important;;cursor: pointer;" @click="openSampleDialog">
          选择答题样本库
        </p>
        <div class="sampleBox">
          <span v-for="(item) in writeSettingForm.sampleLibrary" :key="item.key">
            <span v-if="!item.isType" class="sampleSpan">
              {{ item.label }}
              <i class="el-icon-close" @click="deleteSample(item)" />
            </span>
          </span>
        </div>
      </div>
      <!-- <el-row>
        <p class="project-setting-sub-label">
          * 开启后将会授权登录，提供微信昵称、性别、城市信息
        </p>
      </el-row> -->
      <div class="submit-btn">
        <el-button type="primary" @click="saveSettingHandle">
          保存设置
        </el-button>
      </div>
    </el-form>
    <el-dialog title="选择样本库" :visible.sync="dialogVisible">
      <el-tree
        ref="tree"
        :props="defaultProps"
        :data="data"
        check-strictly
        node-key="key"
        :default-checked-keys="defaultCheckedKeys"
        show-checkbox
        @check="handleCheck"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitSample">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "./mixin"
import {getSettingRequest, saveSettingRequest,typeTree} from "../../../api/project/setting"
import {deepClone} from "../../../utils"

export default {
  name: "WriteSetting",
  mixins: [mixin],
  data() {
    return {
      dateRangeList: [
        {value: 1, label: '总共'},
        {value: 2, label: '每天'},
        {value: 3, label: '每周'},
        {value: 4, label: '每月'}
      ],
      settingRules: {},
      writeSettingForm: {
        // 仅在微信填写
        onlyWxWrite: false,
        // 记录微信用户信息
        recordWxUser: false,
        // 恢复提交数据
        saveSubmitStatus: false,
        // 保存未恢复数据
        saveNotSubmitStatus: false,
        // 密码填写状态
        passwordWriteStatus: false,
        // 填写密码
        writePassword: "",
        // 每个微信答题次数限制
        wxWriteCountLimitStatus: false,
        // 次数
        wxWriteCountLimit: 1,
        // 日期范围
        wxWriteCountLimitDateType: 1,
        // 文案
        wxWriteCountLimitText: "",
        // 每个IP答题次数限制
        ipWriteCountLimitStatus: false,
        // 次数
        ipWriteCountLimit: 1,
        // 日期范围
        ipWriteCountLimitDateType: 1,
        // 文案
        ipWriteCountLimitText: "",
        // 累计答题数量
        totalWriteCountLimitStatus: false,
        // 次数
        totalWriteCountLimit: 1,
        // 日期范围
        totalWriteCountLimitDateType: 1,
        // 文案
        totalWriteCountLimitText: "",
        // 访问时间
        writeInterviewTimeStatus: false,
        // 访问时间是否是一天内的某些小时
        writeInterviewDayTimeStatus: false,
        // 允许访问访问时间范围
        writeInterviewDateTimeRange: [],
        // 允许访问访问日期范围
        writeInterviewDateRange: [],
        // 允许访问访问时间范围
        writeInterviewTimeRange: [],
        // 每周允许周几访问
        writeInterviewTimeWhichDays: [],
        writeInterviewTimeText: "",
        openSample:false,
        openVerificationCodeLogin:false,
        sampleLibrary:[]
      },
      dialogVisible:false,
      defaultProps: {
          children: 'children',
          label: 'label'
      },
      data: [],
      defaultCheckedKeys:[]
    }
  },
  mounted() {
    this.queryUserProjectSetting()
  },
  methods: {
    queryUserProjectSetting() {
      getSettingRequest(this.formKey).then((res) => {
        if (res.data) {
          this.writeSettingForm = res.data
          if(res.data.sampleLibrary.length){
            res.data.sampleLibrary.forEach((item)=>{
              this.defaultCheckedKeys.push(item.key)
            })
          }
          this.getTypeTree()
        }
      })
    },
    saveSettingHandle() {
      this.$refs["writeSettingForm"].validate((valid) => {
        if (valid) {
          this.writeSettingForm.formKey = this.formKey
          saveSettingRequest(this.writeSettingForm).then(() => {
            this.msgSuccess("保存成功")
            this.queryUserProjectSetting()
          })
        } else {
          return false
        }
      })
    },
    openSampleDialog(){
      console.log(this.writeSettingForm.sampleLibrary,'this.writeSettingForm.sampleLibrary')
      this.dialogVisible=true
      this.$nextTick(function(){
        var idArr =[]
        this.writeSettingForm.sampleLibrary.forEach((item) =>{
          idArr.push(item.key)
        })
        console.log(idArr,'idArr')
        this.data.forEach((item)=>{
          this.defaultCheckedKeys=idArr
          this.$refs.tree.setCheckedKeys(idArr)
        })
      })
      
      
    },
    deleteSample(item){
      var idArr =[]
      this.writeSettingForm.sampleLibrary.forEach((item2,index) =>{
        if(item2.key == item.key){
          if(this.defaultCheckedKeys.length){
            this.defaultCheckedKeys.forEach((item3,index3)=>{
              if(item3 === item.key){
                this.defaultCheckedKeys.splice(index3,1)
              }
            })
          }
          this.writeSettingForm.sampleLibrary.splice(index,1)
          this.writeSettingForm.sampleLibrary.forEach((item) =>{
            idArr.push(item.id)
          })
          
        }
      })
      
      this.writeSettingForm.sampleLibrary.forEach((item,index) =>{
        if(item.children){
          var num=0
          item.children.forEach((item2)=>{
            if(!idArr.includes(item2.key)){
              num++
            }
          })
          if(num == item.children.length){
            this.writeSettingForm.sampleLibrary.splice(index,1)
          }
        }
      })
      console.log(this.writeSettingForm.sampleLibrary,'delete----')
    },
    submitSample(){
      this.dialogVisible=false
      this.writeSettingForm.sampleLibrary=this.$refs.tree.getCheckedNodes()
      console.log(this.writeSettingForm.sampleLibrary,'this.writeSettingForm.sampleLibrary')
    },
    handleCheck (data, { checkedKeys }) {
      console.log(data,checkedKeys,'1212')
      let node = this.$refs.tree.getNode(data.key)  
      if (checkedKeys.includes(data.key)) { // 选中
       // getNode(node-key)
        this.selectChildren(data, true) // 选中子节点
        this.parentNodesChange(node) // 选中父节点
      } else {
        
        console.log(node,'node-----')
        this.selectChildren(data, false) // 取消子节点
        this.cancelParentNode(node)
      }
    },
    selectChildren (data, checked) {
      data && data.children && data.children.map((item) => {
        this.$refs.tree.setChecked(item.key, checked)
        if (data.children) {
          this.selectChildren(item, checked)
        }
      })
    },
    cancelParentNode(node){
      if (node.parent) {
        if(node.parent.childNodes && node.parent.childNodes.length){
          var num=0
          node.parent.childNodes.forEach((item) =>{
            if(!item.checked){
              num++
            }
          })
          if(num == node.parent.childNodes.length){
            console.log(node.parent,'name')
            this.$refs.tree.setChecked(node.parent.data.key, false)
          }
        }
        if (node.parent && node.id !== 0) {
          this.cancelParentNode(node.parent)
        }
      }
    },
    // 父级递归
    parentNodesChange (node) {
     
      if (node.parent) {
        for (let key in node) {
          if (key == 'key') {
            // console.log(node[key]);
            this.$refs.tree.setChecked(node, true)
          }
        }
        if (node.parent && node.id !== 0) {
          this.parentNodesChange(node.parent)
        }
      }
    },
    getTypeTree(){
      if(this.writeSettingForm.openSample){
        typeTree().then((res) => {
          if(res.code == 200){
            res.data.forEach((item)=>{
              item.label=item.name
              item.key=item.id
              if(item.libraryList){
                item.libraryList.forEach((item2)=>{
                  item2.label=item2.name
                  item2.key=item.id+'-'+item2.id
                })
                item.children = item.libraryList
              }
            })
            this.data = res.data
            console.log(this.data,'treeData')
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "settting";

.checkbox-group .el-checkbox {
  margin-right: 23px;
}
.sampleBox{
  width:75%;
  margin-left: 10px;
  text-align: left;
}
.sampleSpan{
  display: inline-block;
  position: relative;
  padding-right:16px;
  margin-right:10px;
}
.el-icon-close{
  position:absolute;
  top:-3px;
  right:0;
  color:#999;
  font-size:8px;
}
.sampleList{
  display: flex;
}
</style>

